from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pytesseract
from PIL import Image
import time

# 指定WebDriver路径

# 初始化WebDriver
driver = webdriver.Chrome()

# 打开目标网页
driver.get("http://valser.org/reg/2024/index/identity.html")

# 等待页面加载完成
wait = WebDriverWait(driver, 10)

# 填写手机号
phone_input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#app [placeholder='请输入手机号码']")))
phone_input.send_keys("18801321911")  # 替换成有效的手机号码

# # 选择手机验证码选项
# checktype_radio = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#app [value='1']")))
# checktype_radio.click()

# 刷新验证码并识别
refresh_captcha_button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#app [@click='refreshCaptcha']")))
refresh_captcha_button.click()
time.sleep(2)  # 等待验证码图片加载

# 获取验证码图片
captcha_image_element = driver.find_element(By.CSS_SELECTOR, "#app img[verifySrc]")
captcha_image_location = captcha_image_element.get_attribute('src')

# 下载验证码图片
driver.get(captcha_image_location)
captcha_image = driver.find_element(By.TAG_NAME, "img")
captcha_image_screenshot = captcha_image.screenshot_as_png
with open("captcha.png", "wb") as file:
    file.write(captcha_image_screenshot)

# 使用pytesseract识别验证码
pytesseract.pytesseract.tesseract_cmd = 'path/to/tesseract'  # 请替换为您的Tesseract路径
captcha_text = pytesseract.image_to_string(Image.open("captcha.png"))[0]  # 假设验证码只有一位数字或字母
print("识别的验证码是:", captcha_text)

# 填写验证码
captcha_input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#app [placeholder='请输入图中验证码']")))
captcha_input.send_keys(captcha_text)

# 点击获取短信验证码
get_phone_verify_button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#app .getverify")))
get_phone_verify_button.click()

# 等待短信验证码发送并打印响应
print("等待短信验证码发送...")
time.sleep(10)  # 假设短信验证码发送需要10秒，实际时间可能有所不同

# 打印响应信息
response_message = driver.find_element(By.CSS_SELECTOR, "#app .alert-info").text
print("响应信息:", response_message)

# 关闭WebDriver
driver.quit()